package com.ruike.alisurface.service;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.IntentService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.SystemClock;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.https.MchApiHttp;
import com.ruike.alisurface.ui.adv.Adv_Aty;
import com.ruike.alisurface.utils.CmdUtils;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.SharedUtils;

import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 截屏信息下载类
 */
public class MyScrennService extends IntentService implements ApiListener {
    public final String Tag = "上传截屏信息=";
    Bitmap bitmap1 = null;//位图

    public MyScrennService() {
        super("MyScrennService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        L.i(Tag + "MyScrennService===");
    }

    /**
     * 判断当前应用程序处于前台还是后台  true  后台  false  前台
     */
    public boolean isApplicationBroughtToBackground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            @SuppressLint({"NewApi", "LocalSuppress"}) ComponentName topActivity = tasks.get(0).topActivity;
            return !topActivity.getPackageName().equals(context.getPackageName());
        }
        return false;
    }

    /**
     * 截图并上传
     */
    public void getConfirm_cmd() {
        if (!isApplicationBroughtToBackground(this)) {
            L.i(Tag + "MyScrennService===", ActivityUtils.getTopActivity());
            if (ActivityUtils.getTopActivity() instanceof Adv_Aty) {
                int types = SharedUtils.getInstance().getInt(Constant.AdvType.ADV_TYPE_KEY, Constant.AdvType.NONE);
                L.i(Tag + "MyScrennService===", types);
                if (types == 1) {
                    try {
                        saveBitmapSend(true);
                    } catch (Exception e) {
                        L.i(Tag + "Exception==", e.getMessage());
                    }
                    return;
                } else {
                    bitmap1 = ScreenUtils.screenShot(ActivityUtils.getTopActivity());
                }
            } else {
                bitmap1 = ScreenUtils.screenShot(ActivityUtils.getTopActivity());
            }
            saveBitmapSend(false);
        } else {
            L.i(Tag + "不在前台不截图");
        }
    }

    /**
     * 上传图片
     */
    public void saveBitmapSend(boolean isVideo) {
            // 首先保存图片
            File appDir = new File(Constant.FilePath.SCREENSHOTS_PATH);
            if (!appDir.exists()) {
                appDir.mkdirs();
            }
            long systemTime = System.currentTimeMillis();
            String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date(systemTime));
            String imgName = appDir.getAbsolutePath() + File.separator + "Screenshots-" + fileName + ".png";
            if (isVideo) {
                String cmd = "screencap -p " + imgName;
                CmdUtils.execRootCmd(cmd);
                File file = new File(imgName);
                L.i(Tag + "上传截屏信息图片===", file.getAbsolutePath());
                SystemClock.sleep(50);
                MchApiHttp.getAddScreenshot(this, file);
            } else {
                if (bitmap1 != null) {
                if (ImageUtils.save(bitmap1, imgName, Bitmap.CompressFormat.PNG)) {
                    File file = new File(imgName);
                    L.i(Tag + "上传截屏信息图片===" + file.getAbsolutePath());
                    MchApiHttp.getAddScreenshot(this, file);
                }
            }
        }
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        try {

            L.i(Tag + "MyScrennService===", "开始准备截图");
            getConfirm_cmd();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }


    @Override
    public void onRequestStart(String requestUrl, int requestId) {

    }

    @Override
    public void onRequestComplete(String requestUrl, int requestId) {

    }

    @Override
    public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {

    }

    @Override
    public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {

    }


}